﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace mxplay
{
    public partial class LogWindow : Form
    {
        public LogWindow()
        {

            InitializeComponent();
            AddMessageSafeHolder = new AddMessageSafeHandler(add_message_safe);
        }

        /// <summary>
        /// Thread safe call
        /// </summary>
        /// <param name="message"></param>
        public void AddMessage(string message)
        {
            if (InvokeRequired)
            {
                int thread_id=System.Threading.Thread.CurrentThread.ManagedThreadId;
                object[] args=new object[] { new MessageSafeArgs(message, thread_id) };
                Invoke(AddMessageSafeHolder, args);
            }
            else
            {
                textBox.AppendText(string.Format("[{0}] [UI thread] {1}", DateTime.Now.ToLongTimeString(), message));
                textBox.AppendText(Environment.NewLine);
            }
        }

        private delegate void AddMessageSafeHandler(MessageSafeArgs e);
        private AddMessageSafeHandler AddMessageSafeHolder;
        private void add_message_safe(MessageSafeArgs e)
        {
            textBox.AppendText(string.Format("[{0}] [Thread: 0x{1:X}] {2}", DateTime.Now.ToLongTimeString(), e.ThreadId, e.Message));
            textBox.AppendText(Environment.NewLine);
        }

        class MessageSafeArgs
        {
            public string Message { get; set; }
            public int ThreadId { get; set; }

            public MessageSafeArgs(string message,int thread_id)
            {
                Message = message;
                ThreadId = thread_id;
            }
        }
    }
}
